//
//  SuveryViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class SuveryViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "问卷调查"
        
        InitwViews()
        
    }
    func InitwViews()  {
        
        let array = ["全校问卷","班级排行"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        self.view.addSubview(tableView)
        setUpRefresh()
    }
    func setUpRefresh() {
        if mark == "1" || mark == "3"{
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SuveryViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(SuveryViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SuveryViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    func refresh() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminwebapppi
            
            if mark == "1" {
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "26</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                workArray =  getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            }else if mark == "2" {
                
                let request = requestHeader + "22</t><sch>" + user.schid + "</sch></channel></rss>"
                
                classArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
                
            }else if mark == "3" {
                
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "25</t><sch>" + user.schid + "</sch><top>20</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                teacherArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        tableView.header.endRefreshing()
        
    }
    /**
     加载更多
     */
    func loadMore() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminwebapppi
            pageIndex += 1
            
            if mark == "1" {
                let page: String = String(pageIndex)
                let request = requestHeader + "26</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                workArray.addObjects(from: getData(url, request: request) as [AnyObject])
            }else if mark == "3" {
                let page: String = String(pageIndex)
                let request = requestHeader + "24</t><sch>" + user.schid + "</sch><top>20</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                
                teacherArray.addObjects(from: getData(url, request: request) as [AnyObject])
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        tableView.footer.endRefreshing()
    }
    
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        case 2:
            mark = "3"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if mark == "1" {
            return workArray.count
        }else if mark == "2" {
            return classArray.count
        }else {
            return teacherArray.count
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            return 130
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
        
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            let cellIdentifier = "SuveryTableViewCellIdentifier";
            
            let cell: SuveryTableViewCell = SuveryTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < workArray.count {
                let dic = workArray[indexPath.row] as! JSON
                let time = dic["CreateTime"].stringValue
                let content = dic["Title"].stringValue
                let sender = dic["teaname"].stringValue
                let classname = dic["classname"].stringValue
                
                cell.timeLabel.text = getweek(time)
                cell.contentLabel.text = content
                cell.sender.text = classname + "  " + sender
                
            }
            
            return cell
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                let dic = classArray[indexPath.row] as! JSON
                let classname = dic["classname"].stringValue
                let count = dic["classcon"].stringValue

                cell.classname.text = classname
                cell.count.text = "提交问卷：" + count
            }
            return cell
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: StudentListTableViewCell = StudentListTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                let dic = teacherArray[indexPath.row] as! JSON
                let teaname = dic["teaname"].stringValue
                let count = dic["usercon"].stringValue
                var photo = dic["teaphoto"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = teaname
                cell.count.text = "发布：" + count
                
            }
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /// /webapp/xdc/ShowQuestionnaire.aspx?qid=%@&userid=%@&schserid=%@
        if mark == "1" {
            let user = getUserPojo()
            let dic = workArray[indexPath.row] as! JSON
            let serid = dic["SerID"].stringValue
            let url = server + "/webapp/xdc/ShowQuestionnaire.aspx?qid=" + serid + "&userid=" + user.userid + "&schserid=" + user.schid
            let web = WebViewController()
            web.url = url
            web.titleStr = "问卷调查"
            self.navigationController?.pushViewController(web, animated: true)
        }
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

